package com.jdrx.sw.sewage.service;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import com.jdrx.platform.commons.rest.beans.vo.ResponseVO;
import com.jdrx.platform.commons.rest.exception.BizException;
import com.jdrx.platform.commons.rest.factory.ResponseFactory2;
import com.jdrx.sw.sewage.beans.dto.DevStorageDTO;
import com.jdrx.sw.sewage.beans.dto.DevStorageTypeQueryDTO;
import com.jdrx.sw.sewage.beans.entity.CategoryPO;
import com.jdrx.sw.sewage.beans.entity.DevStoragePO;
import com.jdrx.sw.sewage.beans.entity.DeviceStorageRecordPO;
import com.jdrx.sw.sewage.beans.entity.FactoryPO;
import com.jdrx.sw.sewage.beans.vo.CategoryVO;
import com.jdrx.sw.sewage.beans.vo.DevStorageTypeVO;
import com.jdrx.sw.sewage.beans.vo.FactoryVO;
import com.jdrx.sw.sewage.beans.vo.MaterielVO;
import com.jdrx.sw.sewage.beans.vo.base.PageVO;
import com.jdrx.sw.sewage.common.config.PathConfig;
import com.jdrx.sw.sewage.common.constant.Constant;
import com.jdrx.sw.sewage.common.enums.StorageDevType;
import com.jdrx.sw.sewage.dao.*;
import com.jdrx.sw.sewage.service.base.BaseServiceImpl;
import com.jdrx.sw.sewage.service.common.ExcleExportService;
import com.jdrx.sw.sewage.service.common.SequenceDefineServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.jdrx.sw.sewage.common.constant.Constant.DEVICE_STORAGE;

@Service
public class DevStorageTypeServiceImpl extends BaseServiceImpl {

    public static final Logger logger = LoggerFactory.getLogger(DevStorageTypeServiceImpl.class);

    @Autowired
    private DevStorageTypeDAO devStorageTypeDAO;
    @Autowired
    private DevStorageRecordDAO devStorageRecordDAO;
    @Autowired
    private DevStorageServiceImpl devStorageServiceImpl;
    @Autowired
    private SequenceDefineServiceImpl sequenceDefineServiceImpl;
    @Autowired
    private DevStorageImportServiceImpl devStorageImportServiceImpl;
    @Autowired
    private DevStorageImportCheckServiceImpl devStorageImportCheckServiceImpl;
    @Autowired
    private ExcleExportService excleExportService;
    @Autowired
    private PathConfig pathConfig;
    @Autowired
    private DevStorageDAO devStorageDAO;
    @Autowired
    private CategoryDAO CategoryDAO;
    @Autowired
    private FactoryDAO factoryDAO;
    @Autowired
    private MaterielDAO materielDAO;
    @Autowired
    private CategoryServiceImpl categoryServiceImpl;

    public PageVO<DevStorageTypeVO> selectByPage(DevStorageTypeQueryDTO devStorageTypeQueryDTO) {
        /*PageHelper.startPage(devStorageTypeQueryDTO);
        List<DevStorageTypeVO> devStorageTypeVOS = devStorageTypeDAO.selectByPage(devStorageTypeQueryDTO);
        PageVO<DevStorageTypeVO> devStorageTypeVOPageVO = PageVO.toPageVO(devStorageTypeVOS);
        devStorageTypeVOPageVO.getData().forEach(item -> {
            item.setUseNum(devStorageServiceImpl.countDevNum(StorageDevType.USE.getKey(), item.getId()));
            item.setAttachmentNum(devStorageServiceImpl.countDevNum(StorageDevType.ATTACHMENT.getKey(), item.getId()));
            item.setScrapNum(devStorageServiceImpl.countDevNum(StorageDevType.SCRAP.getKey(), item.getId()));
        });*/
        PageHelper.startPage(devStorageTypeQueryDTO);
        return PageVO.toPageVO(devStorageTypeDAO.selectByPage(devStorageTypeQueryDTO));
    }

    public Map<String, Object> findFactoryAndDevStorageAndMateriel() throws BizException {
        Map<String, Object> map = Maps.newHashMap();
        List<MaterielVO> materielVOS = materielDAO.selectList();
        materielVOS.forEach(item -> {
            item.setDevStorageNames(categoryServiceImpl.selectNameList(item.getId()));
        });
        map.put("categoryAndMateriel", materielVOS);
        map.put("factory", factoryDAO.selectList());
        return map;
    }

    public ResponseVO deviceStorage(DevStorageDTO devStorageDTO, String dataNode) throws BizException {
        String factoryName = devStorageDTO.getFactoryName();
        String categoryName = devStorageDTO.getCategoryName();

        FactoryVO factoryVO = factoryDAO.selectByName(factoryName);
        if (Objects.isNull(factoryVO)) {
            FactoryPO factoryPO = new FactoryPO();
            factoryPO.setName(factoryName);
            factoryDAO.insert(factoryPO);
            devStorageDTO.setFactoryId(factoryDAO.selectNextId() - 1);
        } else devStorageDTO.setFactoryId(factoryVO.getId());

        CategoryVO categoryVO = CategoryDAO.selectByName(categoryName);
        if (Objects.isNull(categoryVO)) {
            CategoryPO categoryPO = new CategoryPO();
            categoryPO.setName(categoryName);
            categoryPO.setMaterielId(devStorageDTO.getMaterielId());
            CategoryDAO.insert(categoryPO);
            devStorageDTO.setCategoryId(CategoryDAO.selectNextId() - 1);
        } else devStorageDTO.setCategoryId(categoryVO.getId());

        if (StringUtils.isNotEmpty(devStorageDTO.getSnNum())) {
            Integer count = devStorageDAO.countDevBYStorageNum(devStorageDTO.getSnNum());
            if (count >= 1) return ResponseFactory2.err("资产编号重复！");
        }

        DevStorageTypeVO devStorageTypeVO = devStorageTypeDAO.findDevStorTypeByMatIdAndCatIdAndDossierSpec(devStorageDTO);
        if (Objects.isNull(devStorageTypeVO)) {
            devStorageTypeVO = new DevStorageTypeVO();
            devStorageDTO.setFactoryIds("," + devStorageDTO.getFactoryId() + ",");
            devStorageDTO.setCreateAt(new Date());
            devStorageDTO.setPlcLogicPoint(0);
            devStorageTypeDAO.add(devStorageDTO);
            devStorageTypeVO.setId(devStorageTypeDAO.selectNextId() - 1);
        } else {
            String orderFactoryIds = devStorageTypeVO.getFactoryIds();
            String addFactoryId = devStorageDTO.getFactoryId() + ",";
            String factoryIds = null;
            if (!orderFactoryIds.contains("," + addFactoryId))
                factoryIds = orderFactoryIds + addFactoryId;
            else factoryIds = orderFactoryIds;

            devStorageTypeDAO.update(devStorageDTO.getAttach(), devStorageTypeVO.getId(), factoryIds);
        }

        DevStoragePO devStoragePO = new DevStoragePO();
        BeanUtils.copyProperties(devStorageDTO, devStoragePO);
        devStoragePO.setStorageTypeId(devStorageTypeVO.getId());
        devStoragePO.setCreateAt(new Date());
        devStoragePO.setDevType(StorageDevType.ATTACHMENT.getKey());
        devStoragePO.setCycleTime(devStorageDTO.getMaintenanceCycleDay());
        devStoragePO.setWorkTime(devStorageDTO.getMaintenanceCycleHour());
        devStoragePO.setPlcLogicPoint(0);
        devStoragePO.setInitWorkTime(0);
        for (int i = 0; i < devStorageDTO.getStorageNum(); i++) {
            devStoragePO.setDeviceNum(String.format("JD%08d", sequenceDefineServiceImpl.increment(Constant.SEQ_SN_KEY, getSQLPerfix(dataNode))));
            devStorageServiceImpl.add(devStoragePO);
        }

        DeviceStorageRecordPO storageRecordPO = new DeviceStorageRecordPO();
        storageRecordPO.setCreateAt(new Date());
        storageRecordPO.setCreateBy(devStorageDTO.getCreateBy());
        storageRecordPO.setStorageTypeId(devStorageTypeVO.getId());
        storageRecordPO.setRecordInfo(String.format(DEVICE_STORAGE, devStorageDTO.getStorageNum()));
        devStorageRecordDAO.add(storageRecordPO);

        return ResponseFactory2.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public void deviceStorageImport(MultipartFile file) throws IOException {
        devStorageImportServiceImpl.deviceStorageImport(file);
    }

    public ResponseVO deviceStorageImportCheck(MultipartFile file) throws IOException {
        return devStorageImportCheckServiceImpl.deviceStorageImportCheck(file);
    }

    public void deviceStorageDownload(HttpServletResponse response) throws BizException {
        String fileName = pathConfig.getDownloadPath() + File.separator + "资产入库导入模板.xlsx";
        excleExportService.exportExcleStreamWithFileName(response, fileName);
    }
}
